import { useState, useEffect } from 'react';
import { cn,getFaviconUrl } from '@/lib/utils';

interface WebsiteFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (website: {name: string, icon: string, url: string}) => void;
  initialData?: {id: number, name: string, icon: string, url: string};
}



export default function WebsiteForm({ isOpen, onClose, onSave, initialData }: WebsiteFormProps) {
  const [name, setName] = useState('');
  const [icon, setIcon] = useState('');
  const [customSvg, setCustomSvg] = useState('');
  const [useCustomSvg, setUseCustomSvg] = useState(false);
  const [useFavicon, setUseFavicon] = useState(false);
  const [faviconUrl, setFaviconUrl] = useState('');
  const [url, setUrl] = useState('');
  const [errors, setErrors] = useState<{name?: string, url?: string, icon?: string}>({});
  // 当URL变化时自动获取favicon
  useEffect(() => {
    if (url.trim()) {
      const favicon = getFaviconUrl(url.trim());
      setFaviconUrl(favicon);
      // 如果是新网站且还没有选择图标，自动使用favicon
      if (!initialData && !icon && !customSvg && !useCustomSvg) {
        setUseFavicon(!!favicon);
      }
    } else {
      setFaviconUrl('');
      setUseFavicon(false);
    }
  }, [url, initialData, icon, customSvg, useCustomSvg]);  

  // 初始化表单数据（编辑模式）
  useEffect(() => {
    if (isOpen) {
      if (initialData) {
        setName(initialData.name);
        setUrl(initialData.url);
        
        // 检查是否是SVG图标
        if (initialData.icon && initialData.icon.startsWith('<svg')) {
          setUseCustomSvg(true);
          setCustomSvg(initialData.icon);
          setIcon('');
        } else {
          setUseCustomSvg(false);
          setCustomSvg('');
          setIcon(initialData.icon);
        }
      } else {
        setName('');
        setIcon('');
        setCustomSvg('');
        setUseCustomSvg(false);
        setUrl('');
        setErrors({});
      }
    }
  }, [isOpen, initialData]);
  
  // 表单验证
  // 简单验证SVG格式
  const isValidSvg = (svg: string): boolean => {
    const trimmedSvg = svg.trim();
    return trimmedSvg.startsWith('<svg') && trimmedSvg.endsWith('</svg>');
  };
  
  // 表单校验函数
  const validateForm = (): boolean => {
    const newErrors: {name?: string, url?: string, icon?: string} = {};
    if (!name.trim()) {
      newErrors.name = '请输入网站名称';
    }
    if (useCustomSvg) {
      if (!customSvg.trim() || !isValidSvg(customSvg)) {
        newErrors.icon = '请输入有效的SVG代码';
      }
    } if (useFavicon){
      if (!/^https?:\/\/.+/.test(faviconUrl.trim())) {
        newErrors.url = '请输入有效的URL（以http://或https://开头）';
    }
    } else {
      if (!icon) {
        newErrors.icon = '请选择图标';
      }
    }
    
    
    if (!url.trim()) {
      newErrors.url = '请输入网站URL';
    } else if (!/^https?:\/\/.+/.test(url.trim())) {
      newErrors.url = '请输入有效的URL（以http://或https://开头）';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
  
    
    if (validateForm()) {
      onSave({
        name: name.trim(),
        icon: useCustomSvg ? customSvg : useFavicon ? faviconUrl : icon,
        url: url.trim()
      });
      onClose();
    }
  };
  
  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={onClose}>
      <div 
        className="bg-white dark:bg-gray-800 rounded-2xl shadow-2xl w-full max-w-md"
        onClick={(e) => e.stopPropagation()}
      >
        {/* 头部 */}
        <div className="p-5 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
          <h3 className="text-xl font-semibold text-gray-900 dark:text-white">
            {initialData ? '编辑网站' : '添加常用网站'}
          </h3>
          <button 
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
          >
            <i className="fa-solid fa-times"></i>
          </button>
        </div>
        
        {/* 表单内容 */}
        <form onSubmit={handleSubmit} className="p-5 space-y-5">
          {/* 网站名称 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              网站名称
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className={cn(
                "w-full px-3 py-2 rounded-lg border focus:outline-none focus:ring-2 focus:ring-blue-500",
                "bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600",
                "text-gray-900 dark:text-gray-100",
                errors.name ? "border-red-500 focus:ring-red-500" : "border-gray-300 dark:border-gray-600"
              )}
              placeholder="输入网站名称"
            />
            {errors.name && (
              <p className="mt-1 text-sm text-red-500">{errors.name}</p>
            )}
          </div>
          
           {/* 图标选择 */}
           <div>
             <div className="flex items-center justify-between mb-2">
               <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                 选择图标
               </label>
               <div className="flex items-center space-x-4">
                 {faviconUrl && (
                   <div className="flex items-center">
                     <span className="text-xs text-gray-500 dark:text-gray-400 mr-2">使用网站图标</span>
                     <label className="relative inline-flex items-center cursor-pointer">
                       <input 
                         type="checkbox" 
                         checked={useFavicon}
                         onChange={(e) => {
                           setUseFavicon(e.target.checked);
                           if (e.target.checked) {
                             setUseCustomSvg(false);
                           }
                         }}
                         className="sr-only peer"
                         disabled={!faviconUrl}
                       />
                       <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-500"></div>
                     </label>
                   </div>
                 )}
                 <div className="flex items-center">
                   <span className="text-xs text-gray-500 dark:text-gray-400 mr-2">使用自定义SVG</span>
                   <label className="relative inline-flex items-center cursor-pointer">
                     <input 
                       type="checkbox" 
                       checked={useCustomSvg}
                       onChange={(e) => {
                         setUseCustomSvg(e.target.checked);
                         if (e.target.checked) {
                           setUseFavicon(false);
                         }
                       }}
                       className="sr-only peer"
                     />
                     <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-500"></div>
                   </label>
                 </div>
               </div>
             </div>
             
             {/* Favicon预览 */}
             {faviconUrl && (
              
               <div className={`mb-4 p-3 rounded-lg border ${useFavicon ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/30' : 'border-gray-200 dark:border-gray-700'}`}>
                 <p className="text-xs text-gray-500 dark:text-gray-400 mb-2">网站图标预览:</p>
                 <div className="flex items-center space-x-4">
                   {faviconUrl}
                   <div className="w-12 h-12 rounded-lg bg-white dark:bg-gray-800 flex items-center justify-center shadow-sm border border-gray-200 dark:border-gray-700">
                     <img 
                       src={faviconUrl} 
                       alt="网站图标" 
                       className="max-w-full max-h-full object-contain"
                       onError={(e) => {
                        console.log(e);
                        
                         (e.target as HTMLImageElement).src = '';
                       }}
                     />
                   </div>
                   <div>
                     <p className="text-xs text-gray-700 dark:text-gray-300">自动获取的网站图标</p>
                     <p className="text-xs text-gray-500 dark:text-gray-400 truncate max-w-[200px]">{faviconUrl}</p>
                   </div>
                 </div>
               </div>
             )}
            
            {useCustomSvg ? (
              <div className="space-y-2">
                <textarea
                  value={customSvg}
                  onChange={(e) => setCustomSvg(e.target.value)}
                  className={cn(
                    "w-full px-3 py-2 rounded-lg border focus:outline-none focus:ring-2",
                    "bg-white dark:bg-gray-700",
                    "text-gray-900 dark:text-gray-100",
                    errors.icon ? "border-red-500 focus:ring-red-500" : "border-gray-300 dark:border-gray-600 focus:ring-blue-500"
                  )}
                  rows={4}
                  placeholder='输入SVG代码，例如：<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 2L2 7l10 5 10-5-10-5z"></path><path d="M2 17l10 5 10-5"></path><path d="M2 12l10 5 10-5"></path></svg>'
                />
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  提示：请确保SVG代码是有效的，建议使用24x24大小的图标。
                </p>
                {errors.icon && (
                  <p className="mt-1 text-sm text-red-500">{errors.icon}</p>
                )}
              </div>
            ) : ("")}
          </div>
          
          {/* 网站URL */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              网站URL
            </label>

            <input
              type="url"
              value={url}
              onChange={(e) => {       
                setUrl(e.target.value)
              }}
              className={cn(
                "w-full px-3 py-2 rounded-lg border focus:outline-none focus:ring-2 focus:ring-blue-500",
                "bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600",
                "text-gray-900 dark:text-gray-100",
                errors.url ? "border-red-500 focus:ring-red-500" : "border-gray-300 dark:border-gray-600"
              )}
              placeholder="https://example.com"
            />
            {errors.url && (
              <p className="mt-1 text-sm text-red-500">{errors.url}</p>
            )}
            </div>


          
          {/* 提交按钮 */}
          <div className="pt-4 flex justify-end">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 mr-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
            >
              {initialData ? '更新' : '添加'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}